var app = getApp()
import qiniuUploader from './qiniuUploader.js'
const formatTime = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

function ajaxPost(url, data, success, fail, ) {
    if (!data.token) {
        data.token = wx.getStorageSync('token')
    }
    wx.request({
        url: app.globalData.ajaxUrl + url,
        header: {
            'content-type': 'application/x-www-form-urlencoded',
        },
        method: 'POST',
        data: data,
        success: function(res) {
            console.group(url)
            console.log('%c 请求路径--->', 'color: #1ba01b', url)
            console.log('%c 请求参数--->', 'color: #1ba01b', data)
            console.log('%c 成功--->', 'color: #1ba01b', res.data)
            console.groupEnd()
            success(res.data);
        },
        fail: function(res) {
            console.group(url)
            console.error('%c 请求路径--->', 'color: #1ba01b', url)
            console.error('%c 请求参数--->', 'color: #1ba01b', data)
            console.error('%c 失败--->', 'color: #d66850', res)
            console.groupEnd()
            wx.showToast({
                title: '网络开了下小差，再试一次吧',
                icon: 'none',
                duration: 2000
            })
        },
    });

}
/**
 * 封装toast
 */
function showToast(type, text, obj) {
    let param = {
        duration: (obj && obj.duration) || 2000,
        mask: (obj && obj.isMask) || true
    }
    switch (type) {
        case 'text':
            {
                param['title'] = text || ''
                param['icon'] = 'none'
                break
            }
        case 'loading':
            {
                param['title'] = text || ''
                param['icon'] = 'loading'
                break
            }
        case 'success':
            {
                param['title'] = text || ''
                param['icon'] = 'success'
                break
            }
        case 'error':
            {
                param['title'] = text || ''
                param['image'] = '/images/error.png'
                break
            }
        default:
            {
                break
            }
    }
    wx.showToast(param)
}
// 七牛云上传
const qiniuUpload = {
    filePath: [],
    result: [],
    fn: {},
    current: 0,
    token: '',
    config: {
        useCdnDomain: false,
        region: null
    },
    getToken: function () {
        ajaxPost('member/up_token', {}, res => {
                console.log(res)
                this.token = res.data.data.uptoken
        })
    },
    upload: function (filePath, success) {
        console.log('filePath', filePath)
       
        this.current = 0
        this.result = []
        this.filePath = filePath
        this.fn = success
        this.loop()
    },
    loop: function () {
        if (this.current < this.filePath.length) {
            console.log('this.current', this.current);
            this.formDataUpload(this.filePath[this.current])
        } else {
            this.callBack()
        }
    },
    formDataUpload(path) {
        let endName = path.split('.').pop()
        var timestamp = (new Date()).getTime();
        qiniuUploader.upload(path, (res) => {
            console.log('succcess', res)
            this.result.push(res)
            this.current++
            this.loop()

          
        }, (error) => {
            console.log('error: ' + error);
        }, {
                region: 'SCN',
                key: `${timestamp}.${endName}`,
                uptoken: this.token,
                uptokenURL: app.globalData.ajaxUrl + 'member/up_token',
            }, (res) => {
                console.log(res)
                wx.showLoading({
                    title: '上传中...',
                    mask: true,
                })
                if (res.progress == 100 && this.current + 1 == this.filePath.length) {
                    wx.showToast({
                        title: '上传成功',
                        icon: 'success',
                        duration: 2000
                    })
                    wx.hideLoading()

                }
                console.log('上传进度', res.progress)
                console.log('已经上传的数据长度', res.totalBytesSent)
                console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
            }, () => {
                // 取消上传
            }, () => {
                // `before` 上传前执行的操作
            }, (err) => {
                wx.hideLoading()
                // `complete` 上传接受后执行的操作(无论成功还是失败都执行)
            });
    },
    callBack: function () {
        this.fn(this.result)
        wx.hideLoading()
    }

}
module.exports = {
    formatTime: formatTime,
    ajaxPost,
    showToast,
    qiniuUpload
}